package com.cino.pet.service.impl;

import com.cino.basic.base.exception.BusinessException;
import com.cino.basic.base.service.BaiduAiAuditService;
import com.cino.basic.util.*;
import com.cino.order.domain.OrderPetAcquisition;
import com.cino.order.mapper.OrderPetAcquisitionMapper;
import com.cino.org.domain.Employee;
import com.cino.org.domain.Shop;
import com.cino.org.mapper.EmployeeMapper;
import com.cino.org.mapper.ShopMapper;
import com.cino.pet.domain.SearchMasterMsg;
import com.cino.basic.base.service.impl.BaseServiceImpl;
import com.cino.pet.domain.SearchMasterMsgAuditLog;
import com.cino.pet.dto.MsgDto;
import com.cino.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.cino.pet.mapper.SearchMasterMsgMapper;
import com.cino.pet.query.SearchMasterMsgQuery;
import com.cino.pet.service.SearchMasterMsgAuditLogService;
import com.cino.pet.service.SearchMasterMsgService;
import com.cino.users.domain.Logininfo;
import com.cino.users.domain.User;
import com.cino.users.mapper.UserMapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private BaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private  EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //1.先获取到userId后再 添加到数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);
        //2.百度AI智能审核
        Boolean boo1 = baiduAiAuditService.imageAudit(msg.getResources());
        Boolean boo2 = baiduAiAuditService.textAudit(msg.getName()+msg.getTitle());
        if(boo1 && boo2){//审核通过，改状态，添加审核日志，找最近的店铺
            msg.setState(1);

            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if(nearestShop != null){//有最近的店铺
               msg.setShopId(nearestShop.getId());
                //SmsUtils.sendSms("121321312321","你有新的订单，请尽快处理");
                //发消息给店铺
                System.out.println("你有新的订单，请尽快处理");
            }else {//nearestShop为null
                //SmsUtils.sendSms("121321312321","你有新的订单，请尽快处理");
                msg.setState(3);//放到寻主池
                System.out.println("附近暂无店铺，请持续关注...");
            }
            searchMasterMsgMapper.update(msg);
            return  new AjaxResult();
        }else{//审核不通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //发消息给用户
            SmsUtils.sendSms("21321312","所填内容存在违规信息，请修改后重新提交！");
            System.out.println("所填内容存在违规信息，请修改后重新提交！");
            searchMasterMsgMapper.del(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息 -- 设置user_id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询已完成寻主消息,分平台管理员和店铺管理员
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(  logininfo.getId());
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return  super.pageQuery(query);
    }
    //管理员查询寻主池的寻主消息，不用区分平台管理员和店铺管理员
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.pageQuery(query);
    }

    //待处理寻主消息
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理寻主消息,分平台管理员和店铺管理员
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(  logininfo.getId());
        if(employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return  super.pageQuery(query);
    }

    @Override
    public void reject(Long id) {
        //寻主消息已分配给店铺，店铺拒接
        //拒单之后放入寻主池 state=3 ,置空店铺id
        searchMasterMsgMapper.reject(id);

    }

    @Override
    public void accept(MsgDto msgDto) {
        //平台将寻主消息分给给你这个店铺
        //店铺接收了，指派一个人去接宠物
        //判断订单是否存在 - 说明有人已经去处理了 -不应该重复接单
        OrderPetAcquisition order=orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());//寻主消息id
        //2天内没有去接 - 将寻主消息派给其他的店铺【不设置 过期了状态会变为-1，故设置为0】
        if(order!=null&&order.getState()==0){//有订单，并且当前订单是待处理 - 处理请求来了
            throw new BusinessException("订单正在处理，请勿重复接单!!!");
        }
        //1.生成收购订单
        SearchMasterMsg msg=searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition newOrder =createOrder(msg,msgDto);
        orderPetAcquisitionMapper.save(newOrder);
         //2.告诉处理人在规定时间内去接回宠物:发短信 2day
        //Employee employee=employeeMapper.loadById(msgDto.getHandler());
        //Smsutils.sendSms(emnlovee.cetPhone)."你有新的计单，请在2大之内夫"+msa.aetAddress()+“标间服物”)
        System.out.println("你有新的订单，请在2天之内去"+msg.getAddress()+"接回宠物");
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        //最后确认时间 -2天之后的此刻
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //order.setPaytype(0); 没有，接宠物的时候才会有
        //order.setstate();-正在处理，待处理e
        //order.setPetId);-没有，宠物接后来之后才会有
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;

    }
}
